package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/20 15:17
 */
public class Flink01_Table_BaseUse {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
    
    
    
        // 1. 需要表的执行环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 2. 把流转成动态表
        Table table = tenv.fromDataStream(stream);
        //table.printSchema();  // 打印表的元数据
        // 3. 在动态表上面执行连续查询
        // select .. from t where id=''
        Table result = table
            .where("id='sensor_1'")
            .select("id, vc");
        // 4. 把查询结果(动态表)转成流
        DataStream<Row> resultStream = tenv.toAppendStream(result, Row.class);
        // 5. 把流进行sink
        resultStream.print();
    
        env.execute();
        
    }
}
